package cn.edu.hbwe.book.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import cn.edu.hbwe.book.entity.Order;
import cn.edu.hbwe.book.entity.OrderItem;
import cn.edu.hbwe.book.entity.Product;
import cn.edu.hbwe.book.utils.DataSourceUtils;

public class OrderItemDao {

	// 添加订单项
	public void addOrderItem(List<OrderItem> orderItems) throws SQLException {
		QueryRunner runner = new QueryRunner();
	
		
		String sql = "insert into orderItem(order_id,product_id,buynum) values(?,?,?)";


		for (OrderItem item:orderItems) {
			String order_id = item.getOrder().getId();
			String p_id = item.getP().getId();
			int item_num = item.getBuynum();
			runner.update(DataSourceUtils.getConnection(),sql,order_id,p_id,item_num);
			
		}
	}

	// 根据订单查找订单项.并将订单项中商品查找到。
		public List<OrderItem> findOrderItemByOrder(final Order order)
				throws SQLException {
			QueryRunner runner = new QueryRunner();
		
			String sql = "select * from orderItem,Products where products.id=orderItem.product_id and order_id=?";

	
			return runner.query(DataSourceUtils.getConnection(),sql, new ResultSetHandler<List<OrderItem>>() {
				public List<OrderItem> handle(ResultSet rs) throws SQLException {

					List<OrderItem> items = new ArrayList<OrderItem>();
					while (rs.next()) {
						OrderItem item = new OrderItem();

						item.setOrder(order);
						item.setBuynum(rs.getInt("buynum"));

						Product p = new Product();
						p.setCategory(rs.getString("category"));
						p.setId(rs.getString("id"));
						p.setDescription(rs.getString("description"));
						p.setImgurl(rs.getString("imgurl"));
						p.setName(rs.getString("name"));
						p.setPnum(rs.getInt("pnum"));
						p.setPrice(rs.getDouble("price"));
						item.setP(p);

						items.add(item);
					}

					return items;
				}
			}, order.getId());
		}
		//根据订单id删除订单项
		public void delOrderItems(String id) throws SQLException {
			QueryRunner runner = new QueryRunner();
		
			
			String sql="delete from orderItem where order_id=?";
		
			
			runner.update(DataSourceUtils.getConnection(),sql,id);
		}

}
